package net.tinyportal.tools.spring;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.tinyportal.javax.portlet.TpPortletContext;
import net.tinyportal.service.PortletService;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/** We need our own FactoryBean because Spring does not offer a way to
 * inject request scoped HttpServletResponse objects.
 * See http://forum.springsource.org/showthread.php?p=298179#post298179 */
public class TpRenderRequestFactoryBean implements FactoryBean<TpPortletContext>, ApplicationContextAware, ServletContextAware {
	@Autowired 
	HttpServletRequest request;

	@Autowired
	ApplicationContext applicationContext;

	@Autowired
	private ServletContext servletContext;

	public TpPortletContext getObject() throws Exception {
		PortletService portletService = applicationContext.getBean(PortletService.class);
		String portletName = null ;
		try {
			RequestAttributes requestAttributes =  RequestContextHolder.currentRequestAttributes();

			if (requestAttributes instanceof ServletRequestAttributes) {
				HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();  
				if (null != request) {
					portletName = (String)request.getAttribute("net.tinyportal.spring.portlet");
				}
			}
		} catch (IllegalStateException e) {
			//on n'est pas dans une requete web
			portletName = (String)servletContext.getAttribute("net.tinyportal.spring.portlet");
		}


		String portletPath = portletService.getPortletPath(portletName);
		TpPortletContext tpPortletContext = new TpPortletContext();
		if(tpPortletContext != null){ applicationContext.getAutowireCapableBeanFactory().autowireBean(tpPortletContext);

			tpPortletContext.setPortletName(portletName);
			tpPortletContext.setPortletPath(portletPath);
		}
		return tpPortletContext;


//		throw new Exception("Erreur à la creation du bean");

	}

	public Class<TpPortletContext> getObjectType() {
		return TpPortletContext.class;
	}

	public boolean isSingleton() {
		return false;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;		
	}
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

}
